package com.iscas.dataaggregation.utils;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iscas.dataaggregation.domain.experiment.OtelLogs;
import com.iscas.dataaggregation.mapper.clickhouse.OtelLogsMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class LogsUtils {

    private static final Logger logger = Logger.getLogger(LogsUtils.class);

    @Autowired
    private OtelLogsMapper otelLogsMapper;

    /**
     * 根据时间范围、命名空间和服务名称查询日志
     *
     * @param startTime   起始时间（毫秒级时间戳）
     * @param endTime     结束时间（毫秒级时间戳）
     * @param namespace   命名空间
     * @param serviceName 服务名称
     * @return 日志列表
     */
    public List<OtelLogs> getLogs(long startTime, long endTime, String namespace, String serviceName) {
        try {
            logger.info("Fetching logs for Service: " + serviceName + " in Namespace: " + namespace);
            logger.info("Time range: " + startTime + " to " + endTime);

            // 构造 ServiceName 格式：/${platform}/${namespace}/${servicename}
            String k8sServiceName = "/k8s/" + namespace + "/" + serviceName;

            Timestamp from = new Timestamp(startTime); // 示例起始时间
            Timestamp to = new Timestamp(endTime);   // 示例结束时间

            List<OtelLogs> logList = otelLogsMapper.findLogsByParams(from,to,k8sServiceName);

            if (logList == null || logList.isEmpty()) {
                logger.warn("No logs found for Service: " + serviceName + " in Namespace: " + namespace);
                return logList;
            }

            logger.info("Total logs found: " + logList.size());
            return logList;

        } catch (Exception e) {
            logger.error("Error occurred while fetching logs for Service: " + serviceName, e);
            throw new RuntimeException("Error fetching logs", e);
        }
    }
}
